<template>
  <div class="flink-jobs">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>Flink作业管理</span>
        </div>
      </template>

      <!-- 作业概览（分组容器） -->
      <div class="job-overview group-card">
        <div class="section-header">
          <h3 class="section-title">作业概览</h3>
        </div>
        <el-row :gutter="12">
          <el-col :span="6">
            <el-card shadow="hover" class="overview-card accent-success">
              <div class="overview-item">
                <div class="overview-value running">{{ jobStats.running }}</div>
                <div class="overview-label">运行中</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="overview-card accent-info">
              <div class="overview-item">
                <div class="overview-value stopped">{{ jobStats.stopped }}</div>
                <div class="overview-label">已停止</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="overview-card accent-danger">
              <div class="overview-item">
                <div class="overview-value failed">{{ jobStats.failed }}</div>
                <div class="overview-label">失败</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="overview-card accent-primary">
              <div class="overview-item">
                <div class="overview-value total">{{ jobStats.total }}</div>
                <div class="overview-label">总作业数</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 搜索和筛选 -->
      <div class="filter-section card-section">
        <div class="section-header">
          <h3 class="section-title">筛选条件</h3>
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="filters.search"
              placeholder="搜索作业名称或ID"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="3">
            <el-select v-model="filters.status" placeholder="作业状态" clearable @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="运行中" value="RUNNING" />
              <el-option label="已完成" value="FINISHED" />
              <el-option label="失败" value="FAILED" />
              <el-option label="已取消" value="CANCELED" />
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-select v-model="filters.autoRecovery" placeholder="自动恢复" clearable @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="启用" value="true" />
              <el-option label="禁用" value="false" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="filters.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-col>
          <el-col :span="4" class="filter-actions">
            <el-button type="primary" @click="handleFilter">筛选</el-button>
            <el-button @click="clearFilters">清除</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 表格工具栏 -->
      <div class="table-toolbar">
        <div class="left">
          <el-button type="success" size="small" @click="handleBatchImport">批量导入</el-button>
          <el-button type="warning" size="small" @click="showRestartDialog = true">一键重启</el-button>
          <el-button type="danger" size="small" @click="showBatchStopDialog = true">批量停止</el-button>
        </div>
        <div class="right">
          <el-button type="primary" size="small" @click="showRegisterDialog = true">注册作业</el-button>
          <el-button size="small" @click="refreshJobs">刷新</el-button>
          <el-dropdown @command="handleColumnToggle">
            <el-button size="small">
              列设置 <el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  v-for="col in availableColumns" 
                  :key="col.prop"
                  :command="col.prop"
                >
                  <el-checkbox 
                    v-model="col.visible" 
                    @change="toggleColumn(col.prop)"
                  >
                    {{ col.label }}
                  </el-checkbox>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 作业列表 -->
      <el-card class="table-card">
        <template #header>
          <div class="section-header">
            <h3 class="section-title">作业列表</h3>
          </div>
        </template>
        <el-table :data="filteredJobs" style="width: 100%" v-loading="loading">
          <el-table-column prop="job_id" label="作业ID" width="120" />
          <el-table-column prop="job_name" label="作业名称" />
          <el-table-column prop="last_status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.last_status)" size="small">
                {{ getStatusText(row.last_status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="auto_recovery" label="自动恢复" width="100">
            <template #default="{ row }">
              <el-tag :type="row.auto_recovery ? 'success' : 'info'" size="small">
                {{ row.auto_recovery ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="last_check_time" label="最后检查" width="180">
            <template #default="{ row }">
              {{ formatTime(row.last_check_time) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <ActionMenu
                :actions="[
                  { label: '详情', onClick: () => viewJobDetail(row) },
                  ...(row.last_status === 'RUNNING' 
                    ? [{ label: '停止', onClick: () => stopJob(row) }]
                    : [{ label: '启动', onClick: () => startJob(row) }])
                ]"
                :primary-count="1"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 作业详情 -->
    <el-dialog v-model="detailVisible" title="作业详情" width="720px">
      <el-descriptions :column="2" border v-if="detailJob">
        <el-descriptions-item label="作业ID">{{ detailJob?.job_id || '-' }}</el-descriptions-item>
        <el-descriptions-item label="作业名称">{{ detailJob?.job_name || '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(detailJob?.last_status || '')" size="small">
            {{ getStatusText(detailJob?.last_status || '') }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="自动恢复">
          <el-tag :type="detailJob?.auto_recovery ? 'success' : 'info'" size="small">
            {{ detailJob?.auto_recovery ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="最后检查">{{ formatTime(detailJob?.last_check_time as any) }}</el-descriptions-item>
        <el-descriptions-item label="模块">{{ detailJob?.module_name || '-' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 注册作业弹窗 -->
    <FlinkJobRegister
      v-model:visible="showRegisterDialog"
      :on-close="() => showRegisterDialog = false"
      :on-submit="handleRegisterJob"
    />

    <!-- 一键重启弹窗 -->
    <FlinkJobRestart
      v-model:visible="showRestartDialog"
      :available-modules="availableModules"
      :running-jobs="runningJobs"
      :on-close="() => showRestartDialog = false"
      :on-submit="handleRestartJobs"
    />

    <!-- 批量停止弹窗 -->
    <FlinkJobBatchStop
      v-model:visible="showBatchStopDialog"
      :available-modules="availableModules"
      :running-jobs="runningJobs"
      :on-close="() => showBatchStopDialog = false"
      :on-submit="handleBatchStopJobs"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, ArrowDown } from '@element-plus/icons-vue'
import ActionMenu from '@/components/ActionMenu.vue'
import { flinkApi } from '@/api/flink'
import type { FlinkJob } from '@/types'
import FlinkJobRegister from '@/components/FlinkJobRegister.vue'
import FlinkJobRestart from '@/components/FlinkJobRestart.vue'
import FlinkJobBatchStop from '@/components/FlinkJobBatchStop.vue'

// 响应式数据
const jobs = ref<FlinkJob[]>([])
const loading = ref(false)
const showRegisterDialog = ref(false)
const showRestartDialog = ref(false)
const showBatchStopDialog = ref(false)
const detailVisible = ref(false)
const detailJob = ref<FlinkJob | null>(null)

// 筛选条件
const filters = reactive({
  status: '',
  autoRecovery: '',
  search: '',
  dateRange: [] as string[]
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})
const totalPages = computed(() => Math.max(1, Math.ceil((pagination.total || 0) / (pagination.size || 1))))

// 作业统计
const jobStats = computed(() => {
  const running = jobs.value.filter(job => job.last_status === 'RUNNING').length
  const stopped = jobs.value.filter(job => job.last_status === 'FINISHED' || job.last_status === 'MANUALLY_STOPPED').length
  const failed = jobs.value.filter(job => job.last_status === 'FAILED').length
  const total = jobs.value.length

  return { running, stopped, failed, total }
})

// 筛选后的作业列表
const filteredJobs = computed(() => {
  let result = jobs.value

  if (filters.status) {
    result = result.filter(job => job.last_status === filters.status)
  }

  if (filters.autoRecovery !== '') {
    const autoRecovery = filters.autoRecovery === 'true'
    result = result.filter(job => job.auto_recovery === autoRecovery)
  }

  if (filters.search) {
    const searchLower = filters.search.toLowerCase()
    result = result.filter(job => 
      job.job_name?.toLowerCase().includes(searchLower) || 
      (job.job_id && job.job_id.toLowerCase().includes(searchLower))
    )
  }

  if (filters.dateRange && filters.dateRange.length === 2) {
    const [startDate, endDate] = filters.dateRange
    result = result.filter(job => {
      if (!job.last_check_time) return false
      const jobTime = new Date(job.last_check_time).getTime()
      const start = new Date(startDate).getTime()
      const end = new Date(endDate).getTime()
      return jobTime >= start && jobTime <= end
    })
  }

  return result
})

// 可用模块
const availableModules = computed(() => {
  const modules = new Set<string>()
  jobs.value.forEach(job => {
    if (job.module_name) {
      modules.add(job.module_name)
    }
  })
  return Array.from(modules).map(module => ({
    moduleName: module,
    jobName: module,
    jarName: '',
    entryClass: ''
  }))
})

// 运行中的作业
const runningJobs = computed(() => {
  return jobs.value
    .filter(job => job.last_status === 'RUNNING')
    .map(job => ({
      jobId: job.job_id || '',
      jobName: job.job_name,
      status: job.last_status
    }))
})

// 列设置
const availableColumns = ref([
  { prop: 'job_id', label: '作业ID', visible: true },
  { prop: 'job_name', label: '作业名称', visible: true },
  { prop: 'last_status', label: '状态', visible: true },
  { prop: 'auto_recovery', label: '自动恢复', visible: true },
  { prop: 'last_check_time', label: '最后检查', visible: true }
])

// 搜索处理
const handleSearch = () => {
  // 实时搜索，不需要额外处理
}

// 筛选处理
const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

// 清除筛选
const clearFilters = () => {
  filters.search = ''
  filters.status = ''
  filters.autoRecovery = ''
  filters.dateRange = []
}

// 刷新作业
const refreshJobs = () => {
  loadJobs()
}

// 列设置
const handleColumnToggle = (prop: string) => {
  // 列切换逻辑
}

const toggleColumn = (prop: string) => {
  // 切换列显示/隐藏
}

// 获取列显示状态
const getColumnVisible = (prop: string): boolean => {
  const column = availableColumns.value.find(col => col.prop === prop)
  return column ? column.visible : true
}

// 加载作业列表
const loadJobs = async () => {
  try {
    loading.value = true
    const response = await flinkApi.getJobs({
      page: pagination.page,
      size: pagination.size
    })
    jobs.value = response.data.items
    pagination.total = response.data.pagination.total
  } catch (error) {
    console.error('Failed to load jobs:', error)
    ElMessage.error('加载作业列表失败')
  } finally {
    loading.value = false
  }
}

// 应用筛选
const applyFilters = () => {
  pagination.page = 1
  loadJobs()
}

// 查看作业详情
const viewJobDetail = (job: FlinkJob) => {
  detailJob.value = job
  detailVisible.value = true
}

// 停止作业
const stopJob = async (job: FlinkJob) => {
  try {
    await ElMessageBox.confirm(
      `确定要停止作业 "${job.job_name}" 吗？`,
      '确认停止',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: 调用停止作业API
    ElMessage.success('作业停止成功')
    loadJobs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('停止作业失败')
    }
  }
}

// 启动作业
const startJob = async (job: FlinkJob) => {
  try {
    await ElMessageBox.confirm(
      `确定要启动作业 "${job.job_name}" 吗？`,
      '确认启动',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: 调用启动作业API
    ElMessage.success('作业启动成功')
    loadJobs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('启动作业失败')
    }
  }
}

// 注册作业
const handleRegisterJob = async (jobData: any) => {
  try {
    // TODO: 调用注册作业API
    console.log('注册作业数据:', jobData)
    ElMessage.success('作业注册成功')
    loadJobs()
  } catch (error) {
    ElMessage.error('作业注册失败')
  }
}

// 批量导入
const handleBatchImport = () => {
  // TODO: 实现批量导入功能
  ElMessage.info('批量导入功能开发中')
}

// 一键重启
const handleRestartJobs = async (config: any) => {
  try {
    // TODO: 调用一键重启API
    console.log('重启配置:', config)
    ElMessage.success('作业重启任务已提交')
    loadJobs()
  } catch (error) {
    ElMessage.error('作业重启失败')
  }
}

// 批量停止
const handleBatchStopJobs = async (config: any) => {
  try {
    // TODO: 调用批量停止API
    console.log('批量停止配置:', config)
    ElMessage.success('作业停止任务已提交')
    loadJobs()
  } catch (error) {
    ElMessage.error('作业停止失败')
  }
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadJobs()
}

const handleCurrentChange = (page: number) => {
  // 兼容“前往第几页”输入越界
  const next = Math.min(Math.max(1, Number(page || 1)), totalPages.value)
  pagination.page = next
  loadJobs()
}

// 工具函数
const getStatusType = (status: string): string => {
  const types: Record<string, string> = {
    'RUNNING': 'success',
    'FINISHED': 'info',
    'MANUALLY_STOPPED': 'warning',
    'FAILED': 'danger',
    'CANCELED': 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status: string): string => {
  const texts: Record<string, string> = {
    'RUNNING': '运行中',
    'FINISHED': '已完成',
    'MANUALLY_STOPPED': '手动停止',
    'FAILED': '失败',
    'CANCELED': '已取消'
  }
  return texts[status] || status
}

const formatTime = (time: string): string => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

// 初始化
onMounted(() => {
  loadJobs()
})
</script>

<style scoped>
.flink-jobs { padding: 0; }

.page-card { background: linear-gradient(180deg, #ffffff 0%, #fafcfe 100%); border: 1px solid #eef2f6; border-radius: 12px; box-shadow: 0 4px 16px rgba(31,35,41,0.06); }

.card-header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 6px; border-bottom: 1px dashed #eef2f6; }

/* 分组容器：与 card-section 统一 */
.group-card { background: linear-gradient(180deg, #ffffff 0%, #fafcfe 100%); border: 1px solid #eef2f6; border-radius: 12px; box-shadow: 0 4px 16px rgba(31,35,41,0.06); padding: 12px; margin-bottom: 16px; }

.job-overview { margin-bottom: 16px; }
.overview-card { text-align: center; border-left: 3px solid var(--accent, #409EFF); background: linear-gradient(180deg, var(--accent-bg, #f7fbff) 0%, #ffffff 60%); box-shadow: 0 2px 10px rgba(31,35,41,0.04); }
.overview-card.accent-success { --accent:#67c23a; --accent-bg:#f0fff7; }
.overview-card.accent-info { --accent:#909399; --accent-bg:#f8f9fb; }
.overview-card.accent-danger { --accent:#f56c6c; --accent-bg:#fff4f4; }
.overview-card.accent-primary { --accent:#409eff; --accent-bg:#f0f7ff; }
.overview-item { padding: 14px; }
.overview-value { font-size: 32px; font-weight: 800; margin-bottom: 6px; }
.overview-label { color: #606266; font-size: var(--font-subtitle); }

.card-section { background: linear-gradient(180deg, #ffffff 0%, #fafcfe 100%); border: 1px solid #eef2f6; border-radius: 12px; box-shadow: 0 4px 16px rgba(31,35,41,0.06); padding: 16px; margin-bottom: 16px; }
.section-header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 6px; margin-bottom: 8px; border-bottom: 1px dashed #eef2f6; }
.section-title { margin: 0; font-size: var(--font-title); font-weight: 700; color: #1f2937; }

.filter-actions { display: flex; gap: 8px; justify-content: flex-end; align-items: center; }

.table-card { margin-top: 8px; background: linear-gradient(180deg, #ffffff 0%, #fafcfe 100%); border: 1px solid #eef2f6; border-radius: 12px; box-shadow: 0 4px 16px rgba(31,35,41,0.06); }

.table-toolbar { display: flex; justify-content: space-between; align-items: center; margin: 12px 0 8px; }

.pagination-wrapper { margin-top: 12px; display: flex; justify-content: flex-end; align-items: center; }
</style> 